import titleBar from '@/components/title_bar/index.vue'
import { tabList, defaultCp, defaultMaxCp } from './constants.js'
import Progress from '@/components/progress/index.vue'
import SlipDel from 'vue-slip-delete'
import initResponseData from './initResponseData'

import { AMAPKEY, asyncLoadAMAP, Getsite } from '@/utils/amap.js'
import { Copy } from '@/utils/object.js'

let vm
let map
let PositionPicker
let isRuning = false
var circleMarker

let loadMap = async (site) => {    
    if(!PositionPicker){
        AMapUI.loadUI(['misc/PositionPicker'], function(_PositionPicker) {
            PositionPicker = _PositionPicker
            loadMap(site)
        })
        return
    }
    let params = {
        zoom: 13,
    }
    let _center
    if (site && map) {
        map.panTo(site)
        return
    }else{
        try{    
            _center = await Getsite()     
            params.center = _center
        }catch(e){
            vm.$toast(e)
        }
    }
    map = new AMap.Map(vm.$refs.map, params)
    var positionPicker = new PositionPicker({
        mode: 'dragMap',//设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
        map: map,
        iconStyle: { //自定义外观
            url: 'https://webapi.amap.com/ui/1.0/assets/position-picker2.png',
            ancher: [24, 40],
            size: [48, 48]
        }
    })
    circleMarker = new AMap.Circle({
        // center: new AMap.LngLat(116.39,39.9),  // 圆心位置
        center: new AMap.LngLat(_center[0], _center[1]),
        radius: defaultCp * 1e3, // 圆半径
        fillColor: 'rgba(94,142,254,0.2)',   // 圆形填充颜色
        strokeColor: '#fff', // 描边颜色
        strokeWeight: 0, // 描边宽度
    })
    map.add(circleMarker)
    // 成功获取信息
    positionPicker.on('success', function (positionResult) {
        vm.cb(positionResult)
        // console.log(position, address, nearestJunction, nearestRoad, nearestPOI)
    })
    // 海上或海外无法获得地址信息
    positionPicker.on('fail', function (positionResult) {
        console.log('fail')
    })
    // 开启定位
    positionPicker.start()
    map.getCity(e => {
        // console.log(e)
        vm.getCityCallback && vm.getCityCallback(e)
    })
}
export default {
    components: {
        titleBar,
        ProgressBar: Progress,
        SlipDel
    },
    data() {
        return {
            loading: -1,
            allCityChecked: false,
            tabInfo: {
                list: tabList,
                activeIndex: 0,
            },
            cityList: [
                {
                    title: '定位区域',
                    citys: [
                    ]
                },
                {
                    title: '全部区域',
                    /**
                     * [name: '']
                     */
                    citys: []
                },
            ],
            openCityList: false,
            dbCityListSelected: [],
            cityListSelected: [],
            key: AMAPKEY,
            addStatus: 0,
            nearestJunction: '',
            progressSumUp: defaultMaxCp,
            minProgress: 1,
            cp: defaultCp,
            poiPickerList: [],
            poiPickerVal: '',
            placeSearch: false,
            isSearch: false,
            currentPosition: {},
            serveList: [
                // {name: '华强北步行街与振兴路交叉口西北方向95米华强北步行街与振兴路交叉口西北方向95米'},
                // {name: 'test'},
            ],
            oldServeItemVm: null,
            citys: [],
            responseCitySelectData: []
        }
    },
    watch: {
        allCityChecked(val) {
            if (val === true) {
                this.openCityList = false
            }
            return val
        },
        cp(v){
            circleMarker.setRadius(v * 1e3)
        }
    },
    created() {
        isRuning = true
        // this.initMap()
        this.initResponseData()

        window.map_callback = async () => {
            if(!isRuning){
                console.log('QAQ')
                return
            }
            // console.log('map_callback')
            initAMapUI()
            //加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
            AMapUI.loadUI(['misc/PositionPicker'], function (_PositionPicker) {
                PositionPicker = _PositionPicker
                loadMap()
            })

            // AMap.service(["AMap.PlaceSearch"], function() { 
            //     vm.placeSearch = new AMap.PlaceSearch({
            //         // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
            //         city: '深圳'
            //     })
            // })
            AMap.plugin('AMap.Autocomplete', function () {
                var autoOptions = {
                    city: '0755',
                    datatype: 'poi',
                    citylimit: true,
                    type: '120201|120302|120301|120300|120200'
                }
                vm.placeSearch = new AMap.Autocomplete(autoOptions)
            })
        }
    },
    methods: {
        onSwitchAllCt(){
            setTimeout(async () => {
                this.loading = 0
                // console.log(this.allCityChecked)
                if(this.allCityChecked){
                    HTTP('app/serviceAreaInfo/insertServiceAreaInfolist', {
                        areaOrRange: 1,
                        areaUids: [],
                        userUid: getuserUid(),
                        createBy: getuserUid(),
                        // 广东省
                        provinceUid: 19,
                        // 深圳市 目前市固定深圳市
                        cityUid: 202,
                        isSZAll: true,
                    }).then(addResponse => {
                        if(addResponse.code !== 200){
                            this.$toast('服务器异常')
                            this.loading = 1
                        }else{
                            // 需要重新走一遍流程，不然无法重置等
                            this.initResponseData(() => {
                                this.$toast('保存成功')
                            })
                        }
                        // close loading
                    })
                }else{
                    // TODO 取消怎么搞？？
                    // 后台说全部删掉。
                    let id = _ => _
                    let dels = this.dbCityListSelected.map(id)
                    const delResponse = await HTTP('app/serviceAreaInfo/deleteServiceAreaInfolistByUid', {
                        uids: this.getuId(dels),                    
                        userUid: getuserUid(),
                    })
                    if(delResponse.code !== 200){
                        this.$toast('服务器异常')
                        this.loading = 1
                        return
                    }
                    console.log(delResponse.data)
                    // 需要重新走一遍流程，不然无法重置等
                    this.initResponseData(() => {
                        this.$toast('保存成功')
                        this.loading = 1
                    })
                }
            }, 100)
            // // this.initResponseData()            
        },
        initResponseData,
        resetPoi() {
            this.poiPickerVal = ''
            this.poiPickerList = []
        },
        slipOpen(vm) {
            // 无需手动关闭
            this.oldServeItemVm = vm
        },
        async del(index) {
            let item = Copy(this.serveList[index])
            this.loading = 0
            console.log(item)
            try {
                const delResponse = await HTTP('app/serviceAreaInfo/deleteServiceAreaInfolistByUid', {
                    uids: [item.uid],                    
                    userUid: getuserUid(),
                })
                if(delResponse.code !== 200){
                    this.$toast('服务器异常')
                    this.loading = 1 
                    return
                }
                // 删除回调
                this.serveList = this.serveList.filter((_, i) => i !== index)
                this.$refs[`slipDel_${index}`][0].setOpen(false)
                this.loading = 1
            } catch (error) {
                this.$toast('数据开小差了')
                this.loading = 1 
            }
        },
        onServeItem() {
            if (this.oldServeItemVm == null) {
                return
            }
            this.oldServeItemVm.setOpen(false)
        },
        readAddServe(){
            if(this.serveList.length >= 3){
                this.$toast('最多添加三条服务范围')
                return
            }
            this.addStatus = 1
        },
        async addServe() {
            // TODO 点击锁
            // TODO 不在深圳范围不让添加
            // feat 服务半径没有重置
            this.loading = 0
            let info = {
                name: this.nearestJunction,
                position: this.currentPosition,
                rangeSize: this.cp,
            }
            let params = {
                areaOrRange: 2,
                userUid: getuserUid(),
                createBy: getuserUid(),
                // 广东省
                provinceUid: 19,
                // 深圳市 目前市固定深圳市
                cityUid: 202,
                longitude: info.position.lng,
                latitude: info.position.lat,
                rangeName: info.name,
                rangeSize: info.rangeSize,
            }
            console.log(info)
            console.log(params)
            try {
                let addServeScopeResponse = await HTTP('app/serviceAreaInfo/insertServiceAreaInfolist', params)
                if(addServeScopeResponse.code !== 200){
                    this.$toast( addServeScopeResponse.msg || '服务器出错啦')
                    this.loading = 1
                    return
                }
                console.log(addServeScopeResponse.data)
                this.serveList.push({
                    ...addServeScopeResponse.data,
                    ...info
                })
                this.addStatus = 0
                this.$toast('添加成功') 
                // 重置
                this.cp = defaultCp
                // 取消按区域的
                this.initResponseData(() => {
                    this.loading = 1  
                })
            } catch (error) {
                this.$toast('数据开小差了')
                this.loading = 1   
            }
        },
        compositionstart() {
            this.isSearch = true
        },
        compositionend() {
            this.isSearch = false
        },
        onPoiItem(item) {
            let { name, location } = item
            if(!location){
                this.$toast('位置不可用')
                return
            }
            console.log(item)
            this.addStatus = 1
            this.nearestJunction = name
            this.currentPosition = location
            loadMap([location.lng, location.lat])
        },
        onpoiPicker() {
            if (this.isSearch) {
                return
            }
            this.placeSearch.search(this.poiPickerVal, (status, result) => {
                if (result.info === 'OK') {
                    // this.poiPickerList = result.poiList.pois
                    // adcode: "440305"
                    // address: "11号线;(在建)12号线(南宝线)"
                    // city: []
                    // district: "广东省深圳市南山区"
                    // id: "BV10244676"
                    // location: c {P: 22.524022, Q: 113.92359599999997, lng: 113.923596, lat: 22.524022}
                    // name: "南山(地铁站)"
                    // typecode: "150500"
                    this.poiPickerList = result.tips.filter(e => e.location)
                }else{
                    console.log(result)
                    this.poiPickerList = []
                }
            })
        },
        POI() {
            this.resetPoi()
            this.addStatus = 2
        },
        switchOptions(index) {
            this.tabInfo.activeIndex = index
            console.log(index)
            if (index === 1) {
                this.initMap()
            }
            if(index === 0){
                this.initResponseData()
            }
        },
        onSwitchCity() {
            if (this.allCityChecked) {
                return
            }
            this.openCityList = !this.openCityList
        },
        clickCityItem(name) {
            if (this.cityListSelected.includes(name)) {
                this.cityListSelected = this.cityListSelected.filter(e => e != name)
            } else {
                this.cityListSelected.push(name)
            }
        },
        /**
         * 
         * @param {Object} e {
         *  district: string
         * }
         */
        getCityCallback(e) {
            console.log(e.district)
            if (this.cityList[0].citys.length > 0) {
                return
            }
            this.cityList = this.cityList.map((item, i) => {
                if (i == 0) {
                    return {
                        ...item,
                        citys: [{ name: e.district }]
                    }
                }
                return item
            })
            // 选中当前定位
            // this.cityListSelected.push(e.district)
        },
        cb(e) {
            console.log('--e--')
            console.log(e)
            if (e.info === 'OK') {
                this.setPOI(e.regeocode.pois[0])
                // console.log(e)
            } else {
                console.log(e.info)
            }
        },
        setPOI(poi){
            this.nearestJunction = poi.name
            this.currentPosition = poi.location
            circleMarker.setCenter(poi.location)//AMap.LngLat(poi.location.longitude, poi.location.latitude))
        },
        resite() {
            loadMap()
        },
        initMap() {
            vm = this
            asyncLoadAMAP()
        },
        progressChange(cp) {
            this.cp = cp //< (+('1' + new Array((this.progressSumUp + '').length - 1).fill(0).join(''))) ? `0${cp}` : `${cp}`
        },
        areaReset() {
            this.cityListSelected = Copy(this.dbCityListSelected)
        },
        getDelectList(originData, currentData){
            return originData.filter(e => !currentData.includes(e))
        },
        getAddList(originData, currentData){
            return currentData.map(e => e) //currentData.filter(e => !originData.includes(e))
        },
        getuId(data){
            return data.map(e => this.citys
                    .find((item) => item.name === e)
                    .areaUid
                )
                .map(areaUid => 
                    this.responseCitySelectData.find((item) => item.areaUid === areaUid)
                    .uid
                )
        },
        async areaSuccess() {
            this.loading = 0
            let getareaUids = data => data.map(e => this.citys
                .find((item) => item.name === e)
                .areaUid
            )
            let dels = this.getDelectList(this.dbCityListSelected, this.cityListSelected)
            let adds = this.getAddList(this.dbCityListSelected, this.cityListSelected)
            // console.log(this.dbCityListSelected)
            // console.log(this.cityListSelected)
            console.log(dels)
            console.log(adds)
            console.log('---')
            console.log(this.getuId(dels))
            console.log(getareaUids(adds))
            // 用户有取消的地区，请求删除
            if(this.getuId(dels).length !== 0){
                const delResponse = await HTTP('app/serviceAreaInfo/deleteServiceAreaInfolistByUid', {
                    uids: this.getuId(dels),                    
                    userUid: getuserUid(),
                })
                if(delResponse.code !== 200){
                    this.$toast('服务器异常')
                    this.addStatus = 1
                    return
                }
                console.log(delResponse.data)
            }
            // 用户有添加的时候，请求添加
            if(getareaUids(adds).length !== 0){
                const addResponse = await HTTP('app/serviceAreaInfo/insertServiceAreaInfolist', {
                    areaOrRange: 1,
                    areaUids: getareaUids(adds),
                    userUid: getuserUid(),
                    createBy: getuserUid(),
                    // 广东省
                    provinceUid: 19,
                    // 深圳市 目前市固定深圳市
                    cityUid: 202,
                    isSZAll: false,
                })
                if(addResponse.code !== 200){
                    this.$toast('服务器异常')
                    this.loading = 1
                    return
                }
            }
            // 重置（取消按范围的）
            this.initResponseData(() => {
                this.$toast('保存成功')
                this.openCityList = false
                this.loading = 1
            })
        }
    },
    destroyed() {
        isRuning = false
        map.destroy()
    }
}